package com.ruoyi.web.service.impl;

import java.util.Arrays;

import com.ruoyi.web.core.config.OSSConfig;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.utils.Constants;
import com.ruoyi.web.service.ChatService;
import com.ruoyi.web.utils.PooledDashScopeObjectFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ChatServiceImpl implements ChatService {
    @Autowired
    private OSSConfig ossConfig;

    public GenerationResult getMessage(String message) throws Exception {
        Constants.apiKey = ossConfig.getApiKey();//设置自己的apiKey
        PooledDashScopeObjectFactory pooledDashScopeObjectFactory =
                new PooledDashScopeObjectFactory();
        GenericObjectPoolConfig<Generation> config = new GenericObjectPoolConfig<>();
        config.setMaxTotal(32);
        config.setMinIdle(32);
        GenericObjectPool<Generation> generationPool =
                new GenericObjectPool<>(pooledDashScopeObjectFactory, config);
        Generation gen = null;
        GenerationResult result = null;
        try {
            Message systemMsg = Message.builder().role(Role.SYSTEM.getValue())
                    .content("You are a helpful assistant.").build();
            //实际内容的输入位置
            Message userMsg = Message.builder().role(Role.USER.getValue()).content(message).build();
            GenerationParam param = GenerationParam.builder().model("qwen-plus")
                    .messages(Arrays.asList(systemMsg, userMsg))
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE).topP(0.8).enableSearch(true)
                    .build();
            gen = generationPool.borrowObject();
            result = gen.call(param);
            System.out.println(result);
        } finally {
            if (gen != null) {
                generationPool.returnObject(gen);
            }
        }
        System.out.println("completed");
        generationPool.close();

        return result;
    }
}
